package org.gl.utils;

import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;

import android.util.Xml;

public class PullXMLReader<T> {

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public List<T> readXML(InputStream inStream, Class className) {

		XmlPullParser parser = Xml.newPullParser();

		try {

			parser.setInput(inStream, "UTF-8");

			int eventType = parser.getEventType();

			T t = null;

			List<T> persons = null;
			Field[] fields = className.getDeclaredFields();
			while (eventType != XmlPullParser.END_DOCUMENT) {

				switch (eventType) {

				case XmlPullParser.START_DOCUMENT:// 文档开始事件,可以进行数据初始化处理

					persons = new ArrayList<T>();

					break;

				case XmlPullParser.START_TAG:// 开始元素事件
					String name = parser.getName().trim();
					if (name.equalsIgnoreCase(className.getSimpleName())) {
						t = (T) className.newInstance();
					} else {
						for (Field field : fields) {
							if (name.equalsIgnoreCase(field.getName())) {
								if (t != null) {
									String firstLetter = field.getName()
											.substring(0, 1).toUpperCase();
									String setMethodName = "set" + firstLetter
											+ field.getName().substring(1);
									Method setMethod = className.getMethod(
											setMethodName, field.getType());
									setMethod.invoke(t,
											new Object[] { parser.nextText() });// 调用对象的setXXX方法
//									System.out.println("key:" + field.getName()
//											+ "value:" + field.get(t));
								}

								break;
							}

						}
					}

					break;

				case XmlPullParser.END_TAG:// 结束元素事件

					if (t != null
							&& parser.getName().equalsIgnoreCase(
									t.getClass().getSimpleName())) {
						persons.add(t);
						t = null;

					}

					break;

				}

				eventType = parser.next();

			}

			inStream.close();

			return persons;

		} catch (Exception e) {

			e.printStackTrace();

		}

		return null;

	}

}
